package videocate

import (
	"context"
	"gitee.com/bobo-rs/creative-framework/pkg/algorithm/treenode"
	"gitee.com/bobo-rs/creative-framework/pkg/sredis"
	"gitee.com/bobo-rs/innovideo-services/consts"
	"gitee.com/bobo-rs/innovideo-services/enums"
	"gitee.com/bobo-rs/innovideo-services/framework/dao"
	"gitee.com/bobo-rs/innovideo-services/framework/model"
	"gitee.com/bobo-rs/innovideo-services/framework/model/entity"
	"gitee.com/bobo-rs/innovideo-services/library/exception"
	"github.com/gogf/gf/v2/frame/g"
	"strconv"
	"time"
)

// SaveCategory 保存视频分类
func (c *sVideoCate) SaveCategory(ctx context.Context, data entity.VideoCategory) error {
	// 保存数据
	_, err := dao.VideoCategory.Ctx(ctx).
		OmitEmpty().
		Save(data)
	if err != nil {
		return exception.New(`保存视频分类失败`)
	}
	return nil
}

// GetCategoryLabelList 获取视频分类标签列表（大类、子类）
func (c *sVideoCate) GetCategoryLabelList(ctx context.Context, pid uint) (list model.VideoCategoryLabelList, err error) {
	list = model.VideoCategoryLabelList{}
	// 获取数据列表
	return c.QueryAndCacheCategoryList(ctx, g.Map{
		dao.VideoCategory.Columns().Pid:    pid,
		dao.VideoCategory.Columns().IsShow: enums.VideoCategoryShowShow,
	}, consts.VideoCategoryLabelCid+strconv.Itoa(int(pid)))
}

// GetCategoryRecommendList 获取推荐栏目列表
func (c *sVideoCate) GetCategoryRecommendList(ctx context.Context) (list model.VideoCategoryLabelList, err error) {
	// 获取数据列表
	return c.QueryAndCacheCategoryList(ctx, g.Map{
		dao.VideoCategory.Columns().Pid:    0,
		dao.VideoCategory.Columns().IsShow: enums.VideoCategoryShowShow,
	}, consts.VideoCategoryLabelTop)
}

// GetCategoryTreeList 获取视频分类树形结构
func (c *sVideoCate) GetCategoryTreeList(ctx context.Context) (treeList []map[string]interface{}, err error) {
	var (
		list model.VideoCategoryTreeList
	)
	err = c.CategoryModel().Scan(ctx, g.Map{}, &list)
	if err != nil {
		return nil, err
	}
	// 构建树形结构
	return treenode.New().BuildTree(list)
}

// GetCategoryDetail 获取视频分类详情
func (c *sVideoCate) GetCategoryDetail(ctx context.Context, id uint) (detail *model.VideoCategoryDetail, err error) {
	detail = &model.VideoCategoryDetail{}
	// 获取视频分类详情
	err = c.CategoryModel().Scan(ctx, g.Map{
		dao.VideoCategory.Columns().Id: id,
	}, &detail)
	return
}

// QueryAndCacheCategoryList 查询并获取视频类目列表
func (c *sVideoCate) QueryAndCacheCategoryList(ctx context.Context, where interface{}, cacheKey string) (list model.VideoCategoryLabelList, err error) {
	list = model.VideoCategoryLabelList{}
	// 获取数据列表
	r, err := sredis.NewCache().GetOrSetFunc(ctx, cacheKey, func(ctx context.Context) (value interface{}, err error) {
		err = c.CategoryModel().Scan(ctx, where, &list)
		if err != nil {
			return nil, exception.New(`暂无数据`)
		}
		return list, err
	}, time.Hour*24)
	if err != nil {
		return nil, err
	}

	// 格式化数据
	if err = r.Scan(&list); err != nil {
		return nil, err
	}
	return
}
